<!-- <template>
  <div class="wrapper">
    <h1>计数器</h1>
    <button @click="increment">增加</button>
    <button @click="decrement">减少</button>

  </div>
</template>

<script setup>


</script>

<style>

</style> -->


<template>
  <div>
    <form @submit.prevent="handleSubmit">
      <input v-model="nickname" type="text" id="nickname" placeholder="请输入昵称" required>
      <textarea v-model="message" id="message" placeholder="请输入留言" required></textarea>
      <button type="submit">提交</button>
    </form>

    <ul>
      <li v-for="(msg, index) in messages" :key="msg.timestamp">
        <strong>{{ msg.nickname }}</strong>: {{ msg.message }} ({{ formatTime(msg.timestamp) }})
        <button @click="deleteMessage(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 定义响应式变量来存储昵称和留言
const nickname = ref('');
const message = ref('');

// 从 localStorage 中获取消息列表
const messages = ref(JSON.parse(localStorage.getItem('messages')) || []);

// 处理表单提交
const handleSubmit = () => {
  const formData = {
    nickname: nickname.value,
    message: message.value,
    timestamp: new Date().toISOString()
  };

  // 添加新的消息
  messages.value.push(formData);

  // 保存到 localStorage
  localStorage.setItem('messages', JSON.stringify(messages.value));

  // 清空输入框
  nickname.value = '';
  message.value = '';

  console.log('留言已成功提交');
};

// 删除留言
const deleteMessage = (index) => {
  messages.value.splice(index, 1);
  localStorage.setItem('messages', JSON.stringify(messages.value));
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
};

// 在组件挂载时从 localStorage 加载消息
onMounted(() => {
  messages.value = JSON.parse(localStorage.getItem('messages')) || [];
});
</script>

<style>
form {
  display: flex;
  flex-direction: column;
  max-width: 300px;
  margin: 0 auto;
}

input, textarea {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100%;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

button:hover {
  background-color: #0056b3;
}

ul {
  max-width: 500px;
  margin: 0 auto;
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

li button {
  margin-top: -10px;
  float: right;
  background-color: #ff4d4d;
  border-color: #ff4d4d;
}

li button:hover {
  background-color: #ff1a1a;
  border-color: #ff1a1a;
}
</style>

